package y_ut.dbtools.exp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import y_ut.dbtools.DBTool;
/**
 * 
 * @author youxz
 *
 */
public class DBDataExport {

	private Logger logger = Logger.getLogger(DBDataExport.class);
	
	private DataSource dataSource;
	
	private String driver;
	private String url;
	private String user;
	private String passwd;
	private String schema;

	public DBDataExport(DataSource dataSource, String schema) {
		super();
		this.dataSource = dataSource;
		this.schema = schema;
	}
	
	
	
	public DBDataExport(String driver,String url, String user, String passwd, String schema) {
		super();
		this.driver = driver;
		this.url = url;
		this.user = user;
		this.passwd = passwd;
		this.schema = schema;
	}



	public boolean export(IExpWriter writer){
		Connection conn = null;
		try {
			writer.open();
			if(this.dataSource!=null){
				conn = this.dataSource.getConnection();
			}else{
				conn = DBTool.connectSQL(driver, url, user, passwd);
			}
			String tableNames[] = DBTool.getTableNames(conn,this.schema);
			Statement state = conn.createStatement();
			for(int i=0;i<tableNames.length;i++){
				logger.info("备份表:"+tableNames[i]);
				int rowCount = 0;
				ResultSet rs = state.executeQuery("SELECT * FROM "+tableNames[i]);
				String colNames[] = DBTool.getColumnNames(rs);
				int colTypes[] = DBTool.getColumnTypes(rs);
				writer.newTable(tableNames[i]);
				writer.writeTableTitle(colNames);
				
				String[] values = new String[colNames.length];
				while(rs.next()){
					
					/*for(int s=0;s<colNames.length;s++){
						values[s] = rs.getString(colNames[s]);
					}*/
					 DBTool.getValues(rs, colTypes, colNames,values);
					writer.writeRowData(values);
					rowCount++;
				}
				logger.info("完成表："+tableNames[i]+",备份记录数："+rowCount);
				rs.close();
			}
			state.close();
			return true;
		} catch (SQLException e) {
			logger.error(e);
			e.printStackTrace();
		}finally{
			writer.close();
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		return false;
	}
	

}
